<?php

namespace app\api\controller;

use app\api\model\Course;
use app\api\controller\NetUtils;
use app\api\model\CourseArticle;
use app\api\model\TalkShow;
use think\Db;
use app\api\model\Banner;
use app\api\model\CountryDegreeMajor;
use app\api\model\UserCountry;
use app\api\model\UserDegree;
use app\api\model\UserMajor;
use app\api\model\Magazine;
use app\api\model\Config;
use app\api\model\Recom;
use think\Log;
// require_once dirname(__DIR__) . '/api_sdk/vendor/autoload.php';

class Index extends Basic
{
    public $types = [
        1=>'免费订阅',
        2=>'非会员试听',
        3=>'非会员试听',
        4=>'非会员试读',
    ];
    /**
     * 初始化方法，所有子类继承
     */
    protected function initialize()
    {
        parent::initialize();
    }


    public function index()
    {
        echo '小程序（北京）科技有限公司 技术支持';
    }

    public function getRecom()
    {
        $recom = new \app\api\model\Recom();
        // 最新的一个首页推送
        $obj = $recom->where('status',1)->order('update_time desc')->find();
        if (!empty($obj)){
            json_success($obj);
        }
        json_success([]);
    }

    /**
     * 是否开启绑定手机
     */
    public function skip_bind_mobil_switch(){
        //实例化数据库
        $config =new \app\api\model\Config();

        $info = $config->where(array('key'=>'skip_bind_mobil_switch'))->value('value');

        json_success($info);
    }

    /**
     * 用户选择国家学位及专业
     */
    public function check_country(){
        $country_ids = input('country_ids/a');
        $degree_ids = input('degree_ids/a');
        $major_ids = input('major_ids/a');
        $user_id = input('user_id');
        $type = input('type',1);

        if(!$country_ids){
            json_fail('请选择国家');
        }
        if(!$degree_ids){
            json_fail('请选择学位');
        }
        if(!$major_ids){
            json_fail('请选择专业');
        }
        if(!$user_id){
            json_fail('获取用户id失败');
        }

        //实例化数据库
        $user = new \app\api\model\User();
        $userCountry = new UserCountry();
        $userDegree = new UserDegree();
        $userMajor = new UserMajor();
        $countryDegreeMajor = new CountryDegreeMajor();

        $saveData = array(
            'user_type'=>$type
        );
        $user_id = decode($user_id);
        $info = $user->where(array('id'=>$user_id))->update($saveData);

        if($info === false){
            json_fail('设置失败');
        }

        //存国家
        $userCountry->add($country_ids,$user_id);
        //存学位
        $userDegree->add($degree_ids,$user_id);
        //存专业
        $userMajor->add($major_ids,$user_id);
        //存国家,学位,专业关联
        $countryDegreeMajor->add(2,$user_id,$country_ids,$degree_ids,$major_ids);

        json_success('添加成功');
    }

    /**
     * 更新用户地址
     */
    public function save_address(){
        $country = input('country');
        $province = input('province');
        $city = input('city');
        $user_id = input('user_id');

        if(!$country){
            json_fail('获取国家错误');
        }
        if(!$province){
            json_fail('获取省份错误');
        }
        if(!$city){
            json_fail('获取城市错误');
        }
        if(!$user_id){
            json_fail('获取用户id失败');
        }

        //实例化数据库
        $saveData = array(
            'country'=>$country,
            'province'=>$province,
            'city'=>$city
        );

        //实例化数据库
        $user = new \app\api\model\User();
        $user_id = decode($user_id);
        $info = $user->where(array('id'=>$user_id))->update($saveData);


        if($info === false){
            json_fail('操作失败');
        }
        json_success('更新位置成功');
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 首页banner列表
     */
    public function get_banner_list()
    {
        //实例化数据库
        $banner = new Banner();
        $list = $banner->index();
        if (!$list) {
            json_success([]);
        }
        json_success($list);
    }

    /**
     * 首页杂志列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_magazine_list()
    {
        $magazine=new Magazine();
        $limitres = Db('site')->where(['name'=>'首页杂志数量'])->find();
        $limit = $limitres?$limitres['value']:7;
        $list= $magazine->field('id,title,stage,picture,top_picture')->where('status',1)->order('date_issue desc')->page(1,$limit)->select();
        if (!empty($list)){
            json_success($list);
        }
        json_success([]);

    }

    /**
     * 获取首页小课列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function course_list()
    {
        $Course = new Course();
        $limitres = Db('site')->where(['name'=>'首页小课数量'])->find();
        $limit = $limitres?$limitres['value']:6;
        $list=$Course->field('id,title,hits,sub_title,ctype,picture,type,cover')->where("status=1 and is_video=0")->limit($limit)->order('index_sort desc,sort desc,create_time desc')->page(1,$limit)->select();
        if($list) {
            foreach ($list as $key => $value) {
                $list[$key]['hits'] = 0;
                $list[$key]['is_video'] = 0;
                $list[$key]['praise'] = 0;
                $mo = new \app\api\model\CourseArticle();
                $objs = $mo->where('course_id',$value['id'])->select();
                if($objs) {
                    foreach ($objs as $obj) {
                        if($obj['video_url']) {
                            $list[$key]['is_video'] = 1;
                        }
                        $list[$key]['hits'] = $list[$key]['hits']+$obj['hits']+$obj['base_hits'];
                        $praiseobj = Db('praise')->where('type=1 and oid='.$obj['id'])->count();
                        $list[$key]['praise'] = $list[$key]['praise']+$obj['base_praise']+$praiseobj;
                    }
                }
                $list[$key]['hits'] = $this->formatNum((int)$list[$key]['hits']);
                $list[$key]['praise_num'] = $this->formatNum((int)$list[$key]['praise']);
                $list[$key]['type'] = isset($this->types[$list[$key]['type']])?$this->types[$list[$key]['type']]:'';
            }
        }
        if (!empty($list)){
            json_success($list);
        }
        json_success([]);
    }

    /**
     * 首页 TalkShow 列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function talk_show_list()
    {
        $Course = new Course();
        $limitres = Db('site')->where(['name'=>'首页视频数量'])->find();
        $limit = $limitres?$limitres['value']:6;
        $list=$Course->field('id,title,hits,sub_title,picture,video_image,cover')->where("status=1 and is_video=1")->limit($limit)->order('index_sort desc,sort desc,create_time desc')->page(1,$limit)->select();
        if($list) {
            foreach ($list as $key => $value) {
                $list[$key]['duration']='';
                $list[$key]['hits'] = 0;
                $praise = 0;
                $list[$key]['is_video'] = 0;
                $mo = new \app\api\model\CourseArticle();
                $objs = $mo->where('course_id',$value['id'])->select();
                if($objs) {
                    foreach ($objs as $obj) {
                        if($obj['video_url']) {
                            $list[$key]['is_video'] = 1;
                        }
                        $list[$key]['hits'] = $list[$key]['hits']+$obj['hits']+$obj['base_hits'];
                        $praiseobj = Db('praise')->where('type=1 and oid='.$obj['id'])->count();
                        $praise = $praise+$praiseobj+$obj['base_praise'];
                    }
                }
                $list[$key]['hits'] = $this->formatNum((int)$list[$key]['hits']);
                $list[$key]['praise_num'] = $this->formatNum((int)$praise);
                !$list[$key]['video_image'] && $list[$key]['video_image'] = $list[$key]['picture'];
            }
        }
        if (!empty($list)){
            json_success($list);
        }
        json_success([]);

        // $status['status']=['eq',1];
        // $TalkShow=new TalkShow();
        // $list=$TalkShow->field('id,title,picture,author,hits,base_hits,base_praise,duration')->where($status)->where('status',1)->order('sort')->limit(5)->select();
        // foreach ($list as $k=>$v){
        //     if ($v['duration']>=3600){
        //         //求小时数
        //         $hour=(int)($v['duration']/3600);
        //         $s=$v['duration']%3600;
        //         $minute=(int)($s/60);
        //         $s=$v['duration']%60;
        //         $s=$s%60;
        //         $list[$k]['duration']=$hour.':'.$minute.':'.$s;
        //     }else{
        //         $list[$k]['duration']=date('i:s',$v['duration']);
        //     }
        // }
        // if($list) {
        //     foreach ($list as $key => $value) {
        //         $list[$key]['hits'] = $this->formatNum($list[$key]['hits']+$list[$key]['base_hits']);
        //     }
        // }

        // if (!empty($list)){
        //     json_success($list);
        // }
        // json_success([]);
    }


    /**
     * 年份杂志订阅返回 年份杂志与半年杂志价格
     */
    public function subscribe_price()
    {
        $magazine_annual_price=Config::getByKey('magazine_annual_price');  //全年价格
        $magazine_half_year_price=Config::getByKey('magazine_half_year_price'); //半年价格

         $data['magazine_annual_price']= $magazine_annual_price->value/100;
         $data['magazine_half_year_price']= $magazine_half_year_price->value/100;

        if (!empty($data)){
            json_success($data);
        }
        json_success([]);
    }

    // 开屏广告
    public function get_index_ad()
    {
        $res = Db('site')->where(['name'=>'开屏图片'])->find();
        if($res){
            json_success(['image'=>$res['url'],'url'=>$res['value']]);
        }
    }

    // VIP广告
    public function get_vip_ad()
    {
        $res = Db('site')->where(['name'=>'VIP广告位'])->find();
        if($res){
            json_success(['image'=>$this->exchange_img($res['url']),'url'=>$res['value'],'can_video'=>0]);
        }
    }

    public function getWdPush()
    {
        $getArr = $_GET;
        $postArr = $_POST;
        // Log::write(111,'notice');
        // Log::write(json_encode($postArr),'notice');
        if(isset($postArr['content']['type']) && $type = $postArr['content']['type']) {

            // 支付完成
            if($type=='weidian.order.already_payment') {
                // Log::write(json_encode($postArr['content']),'notice');
                $message = $postArr['content']['message'];
                $arr['order_id'] = $message['order_id'];

                $arr['phone'] = $message['buyer_info']['phone'];
                $items = $message['items'];
                $arr['title'] = '';
                $data = [];
                if($items) {
                    foreach ($items as $key => $value) {
                        preg_match_all('/\#.+\#/', $value['item_name'], $titlearr);
                        if(isset($titlearr[0][0])) {
                            list($name,$id) = explode('_', trim($titlearr[0][0],'#'));
                        } else {
                            echo json_encode(['status'=>'success']);
                            return ;
                        }
                        $data[] = [
                            'num'=>$value['quantity'],
                            'name'=>isset($name)&&$name?$name:'',
                            'id'=>isset($id)&&$id?$id:'',
                        ];
                        $arr['title'] = $arr['title'].$value['item_name'].' ';
                    }
                }
                $arr['data'] = json_encode($data);
                $arr['code'] = $this->randomstring();
                Db('wdcode')->insert($arr);

            }

        }
        echo json_encode(['status'=>'success']);
    }

    public function getRandomString($len, $chars=null)  
    {  
        if (is_null($chars)) {  
            $chars = "0123456789abcdefghijklmnopqrstuvwxyz";  
        }  
        mt_srand(10000000*(double)microtime());  
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {  
            $str .= $chars[mt_rand(0, $lc)];  
        }  
        return $str;  
    } 

    public function makeVip()
    {
        $data[] = [
            'num'=>1,
            'name'=>'会员',
            'id'=>0,
        ];
        $arr['data'] = json_encode($data);
        $arr['code'] = $this->getRandomString(8);
        $arr['title'] = '会员码';
        Db('wdcode')->insert($arr);
    }

    public function makeDzk($title='',$id=0)
    {
        // $data[] = [
        //     'num'=>1,
        //     'name'=>'电子刊',
        //     'eid'=>$id,
        // ];
        $arr['eid'] = $id;
        $arr['status'] = 1;
        $arr['create_time'] = time();
        $arr['update_time'] = time();
        $arr['code'] = $this->getRandomString(10);
        // $arr['title'] = $title.' '.'#电子刊_'.$id.'#';
        Db('ebook_code')->insert($arr);
    }

    public function MakeMuchVip($num=1000)
    {
        for ($i=0; $i < $num; $i++) { 
            $this->makeVip();
        }
    }

    public function makeMuchDzk($num=100,$title='',$id='')
    {
        for ($i=0; $i < $num; $i++) { 
            $this->makeDzk($title,$id);
        }
    }



}
